﻿namespace Company.LiveCodingTV.Code
{
    using System;
    using System.Diagnostics;
    using System.Windows.Controls;
    using System.Windows.Threading;

    /// <summary>
    /// Interaction logic for MyControl.xaml
    /// </summary>
    public partial class MyControl : UserControl
    {
        private PerformanceCounter counter;

        /// <summary>
        /// Initializes a new instance of the <see cref="MyControl"/> class.
        /// </summary>
        public MyControl()
        {
            this.InitializeComponent();

            this.counter = new PerformanceCounter();
            this.counter.CategoryName = "Processor";
            this.counter.CounterName = "% Processor Time";
            this.counter.InstanceName = "_Total";

            var timer = new DispatcherTimer();
            timer.Interval = new TimeSpan(0, 0, 0, 3);
            timer.Tick += this.Timer_tick;
            timer.Start();
        }

        /// <summary>
        /// Handles the tick event of the Timer control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        private void Timer_tick(object sender, EventArgs e)
        {
            var time = DateTime.Now;
            this.NowControl.Text = time.ToString("HH:mm");

            var value = this.counter.NextValue();
            System.Threading.Thread.Sleep(1000);
            Debug.WriteLine("_Total = {0}", value);
            
            if (value < 0)
            {
                value = 0;
            }

            if (value >= 99)
            {
                value = 99;
            }

            this.CPU.Value = value;
            this.CPUPERCENT.Content = ((int)value).ToString();
        }
    }
}